/*
 *              Copyright (C) 2011 The MusicMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *            http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.musicmod.plugin.socialize.microblog;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class AuthorizationActivity extends Activity {

	private Handler mHandler;
	private ProgressDialog mSpinner;
	private EditText mUsername;
	private EditText mPassword;
	private Button mSave;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.authorize);
		getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);

		mSpinner = new ProgressDialog(this);
		mSpinner.setMessage(getString(R.string.processing));
		mSpinner.setCancelable(true);
		mSpinner.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				finish();
				return;
			}
		});

		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case Constants.PROCESS_START:
					mSpinner.show();
					break;
				case Constants.PROCESS_STOP:
					mSpinner.dismiss();
					finish();
					break;
				}
			}
		};

		mUsername = (EditText) findViewById(R.id.username);
		mPassword = (EditText) findViewById(R.id.password);
		mSave = (Button) findViewById(R.id.save);

		((Button) findViewById(R.id.cancel))
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						finish();
					}
				});

		mSave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String username = mUsername.getText().toString();
				String password = mPassword.getText().toString();
				saveUserCredentials(username, password);
			}
		});

	}

	private void saveUserCredentials(final String username,
			final String password) {

		mHandler.sendEmptyMessage(Constants.PROCESS_START);

		Thread thread = new Thread() {
			public void run() {

				try {
					String api_base = SharedPrefsUtils.getStringPreference(
							AuthorizationActivity.this, Constants.KEY_API_BASE,
							Constants.DEFAULT_API_BASE);

					HttpResponse response = null;
					DefaultHttpClient client = new DefaultHttpClient();
					HttpContext localContext = new BasicHttpContext();
					HttpPost httpPost = new HttpPost(
							Constants.PUBLIC_TIMELINE_ENDPOINT(api_base));

					BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
					UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
							username, password);
					AuthScope scope = new AuthScope(AuthScope.ANY_HOST,
							AuthScope.ANY_PORT, AuthScope.ANY_REALM);
					credsProvider.setCredentials(scope, creds);
					client.setCredentialsProvider(credsProvider);
					response = client.execute(httpPost, localContext);

					Log.d(Constants.LOG_TAG, "Test connection. response: "
							+ String.valueOf(response.getStatusLine()));

					if (response.getStatusLine().getStatusCode() == 200) {
						SharedPrefsUtils.setStringPreference(
								AuthorizationActivity.this,
								Constants.KEY_USERNAME, username);
						SharedPrefsUtils.setStringPreference(
								AuthorizationActivity.this,
								Constants.KEY_PASSWORD, password);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				mHandler.sendEmptyMessage(Constants.PROCESS_STOP);
			}
		};
		thread.start();

	}
}